package com.hjx.windowtool.file;


import java.nio.file.FileSystems;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;

public class FileWatch {
	public static void main(String[] args) throws Exception {
		final WatchService watchService = FileSystems.getDefault().newWatchService();
		Paths.get("D:\\img").register(watchService, StandardWatchEventKinds.ENTRY_MODIFY,StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_DELETE);
		new Thread(new Runnable() {
			public void run() {
				while (true) {
					try {
						WatchKey key = watchService.take();
						System.out.println(key);
						List<WatchEvent<?>> pollEvents = key.pollEvents();
						for (WatchEvent<?> event : pollEvents) {
							try {
								System.out.println("[" + event.context() + "]文件发生了[" + event.kind() + "]事件" + event.count());
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
						key.reset();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
}
